import configparser
import json
from datetime import datetime
import requests
from modules.logger_config import setup_logger

# 使用统一的日志配置
logger = setup_logger('ApiClient')

class ApiClient:
    def __init__(self, config_path, login_manager):
        # 加载配置文件中的多个部分
        self.config = self._load_config(config_path)
        self.login_manager = login_manager  # 注入登录管理器

    # 修改_load_config方法，确保编码参数正确设置
    def _load_config(self, config_path):
        """加载API相关配置"""
        config = configparser.ConfigParser()
        config.read(config_path, encoding='utf-8')  # 确保有空格和正确的引号
        return config  # 返回完整配置对象

    def _build_params(self, interface_type):
        """构建请求参数（根据接口类型使用不同的模板）"""
        username = self.login_manager.config['username']
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 根据接口类型选择对应的参数模板
        params_section = f'Params_{interface_type.capitalize()}'
        
        if params_section not in self.config:
            logger.error(f"未找到接口类型 {interface_type} 的参数配置")
            return None
            
        return json.loads(
            self.config[params_section]['template']
            .replace("{username}", username)
            .replace("{timestamp}", timestamp)
        )

    def call_backend(self, interface_type):
        """调用后端接口，根据interface_type参数选择对应的配置
        interface_type: str - 'peishu'(配属) 或 'daxiu'(大修)
        """
        # 验证接口类型
        if interface_type not in ['peishu', 'daxiu']:
            logger.error(f"无效的接口类型: {interface_type}，必须是 'peishu' 或 'daxiu'")
            return None
        
        interface_name = "配属" if interface_type == 'peishu' else "大修"
        logger.info(f"开始调用{interface_name}后端接口")
        backend_section = f'Referer_{interface_type.capitalize()}'
        referer_url = self.config[backend_section]['referer']
        logger.info(f"{interface_name}接口Referer: {referer_url}")

        try:
            # 获取Cookie
            cookie_header = self.login_manager.get_cookie_header()
            if not cookie_header:
                logger.error(f"{interface_name}任务执行失败：未登录或Cookie为空")
                return None
                
            headers = {
                "Cookie": cookie_header,
                "Content-Type": "application/json",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36",
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
                "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
                "Accept-Encoding": "gzip, deflate, br",
                "Connection": "keep-alive",
                "Cache-Control": "max-age=0",
                "Referer": referer_url 
            }
            
            # 构建参数
           # params = self._build_params(interface_type)
           # if not params:
           #     return None
            
            # 获取对应接口的配置
            backend_section = f'Backend_{interface_type.capitalize()}'     
            if backend_section not in self.config:
                logger.error(f"未找到接口类型 {interface_type} 的后端配置")
                return None
                
            url = self.config[backend_section]['url']
            method = self.config[backend_section]['method']
            
            # 从配置文件中读取是否启用分页
            enable_pagination = self.config[backend_section].getboolean('enable_pagination', fallback=True)
            logger.info(f"{interface_name}接口是否启用分页: {enable_pagination}")
            logger.info(f"{interface_name}接口URL: {url}")
            logger.info(f"{interface_name}接口方法: {method}")

            # 如果启用分页查询
            if enable_pagination:
                # 尝试从配置中获取分页参数，如果不存在则使用默认值
                page_param_name = self.config[backend_section].get('page_param_name', 'page')
                page_size_param_name = self.config[backend_section].get('page_size_param_name', 'pageSize')
                page_size = int(self.config[backend_section].get('page_size', '100'))  # 默认每页100条
                
                # 存储所有页面的数据
                all_data = []
                current_page = 1
                has_more_data = True
                
                # 从配置中获取分页信息的路径，使用点号分隔表示嵌套路径
                total_items_path = self.config[backend_section].get('total_items_path', 'total')
                data_path = self.config[backend_section].get('data_path', 'rows')
                has_next_page_path = self.config[backend_section].get('has_next_page_path', '')
                
                # 初始化参数
                paginated_params = {}
                paginated_params[page_size_param_name] = page_size
                
                logger.info(f"开始分页查询，每页{page_size}条数据")
                
                while has_more_data:
                    # 设置当前页码
                    paginated_params[page_param_name] = current_page
                    
                    # 每次查询都重写URL，替换其中的分页参数占位符
                    page_url = url.format(page=current_page, pageSize=page_size)
                    logger.info(f"查询第{current_page}页(URL: {page_url})数据")

                    # 发送请求
                    if method.upper() == 'GET':
                        response = requests.request(
                            method=method,
                            url=page_url,
                            params=paginated_params,
                            headers=headers
                        )
                    else:
                        response = requests.request(
                            method=method,
                            url=page_url,
                            json=paginated_params,
                            headers=headers
                        )
                    
                    response.raise_for_status()
                    response_data = response.json()
                    
                    # 提取当页数据
                    page_data = response_data
                    for path_part in data_path.split('.'):
                        if isinstance(page_data, dict) and path_part in page_data:
                            page_data = page_data[path_part]
                        else:
                            page_data = []
                            break
                    
                    # 添加到总数据列表
                    if isinstance(page_data, list):
                        all_data.extend(page_data)
                        logger.info(f"已获取第{current_page}页，数据量: {len(page_data)}，累计: {len(all_data)}")
                    else:
                        logger.warning(f"第{current_page}页数据格式异常，非列表类型")
                        has_more_data = False
                        break
                    
                    # 检查是否还有下一页
                    # 1. 如果配置了has_next_page_path，则使用它来判断
                    if has_next_page_path:
                        has_next_page = response_data
                        for path_part in has_next_page_path.split('.'):
                            if isinstance(has_next_page, dict) and path_part in has_next_page:
                                has_next_page = has_next_page[path_part]
                            else:
                                has_next_page = False
                                break
                        has_more_data = has_next_page
                    else:
                        # 2. 否则通过比较总条数和已获取条数来判断
                        total_items = response_data
                        for path_part in total_items_path.split('.'):
                            if isinstance(total_items, dict) and path_part in total_items:
                                total_items = total_items[path_part]
                            else:
                                total_items = len(all_data)
                                break
                        
                        if isinstance(total_items, int):
                            has_more_data = len(all_data) < total_items
                        else:
                            # 如果没有总条数信息，假设没有更多数据
                            has_more_data = False
                    
                    # 增加页码
                    current_page += 1
                    
                    # 为了避免无限循环，设置最大页码限制
                    if current_page > 1000:
                        logger.warning(f"已达到最大查询页码限制(1000)")
                        break
                # 记录日志页数和数据
                logger.info(f"分页查询完成，共获取{len(all_data)}条数据， {all_data}")
            
                
                # 计算总页数
                total_pages = (len(all_data) + page_size - 1) // page_size
                 # 记录日志
            
                return {
                    'total': len(all_data),
                    'rows': all_data,
                    'pages': total_pages,
                    'message': 'success'
                }
            else:
                # 不分页查询，直接发送请求
                if method.upper() == 'GET':
                    response = requests.request(
                        method=method,
                        url=url,
                        params=params,
                        headers=headers
                    )
                else:
                    response = requests.request(
                        method=method,
                        url=url,
                        json=params,
                        headers=headers
                    )
                
                response.raise_for_status()
                data = response.json()
                logger.info(f"{interface_name}后端接口调用成功")
                # 记录日志
                logger.info(f"{interface_name}后端接口返回数据: {data}")
                return data
        except Exception as e:
            logger.error(f"{interface_name}后端接口调用失败: {str(e)}")
            return None

    def push_data(self, data, interface_type):
        """推送数据到服务器，根据interface_type参数选择对应的配置
        interface_type: str - 'peishu'(配属) 或 'daxiu'(大修)
        """
        # 验证接口类型
        if interface_type not in ['peishu', 'daxiu']:
            logger.error(f"无效的接口类型: {interface_type}，必须是 'peishu' 或 'daxiu'")
            return False
        
        interface_name = "配属" if interface_type == 'peishu' else "大修"
        
        if not data:
            logger.warning(f"{interface_name}无数据可推送")
            return False
        
        logger.info(f"准备推送{interface_name}数据")

        try:
            # 获取对应接口的推送配置
            push_section = f'Push_{interface_type.capitalize()}'
            
            if push_section not in self.config:
                logger.error(f"未找到接口类型 {interface_type} 的推送配置")
                return False
                
            url = self.config[push_section]['url']
            method = self.config[push_section]['method']
            
            logger.info(f"{interface_name}推送URL: {url}")
            logger.info(f"{interface_name}推送方法: {method}")
            
            response = requests.request(
                method=method,
                url=url,
                json=data
            )
            response.raise_for_status()
            logger.info(f"{interface_name}数据推送成功，状态码: {response.status_code}")
            return True
        except Exception as e:
            logger.error(f"{interface_name}数据推送失败: {str(e)}")
            return False